import { defineStore } from "pinia";
import {
    getVersionApi, addVersionApi
    , delVersionApi
} from "@/Api/Version";
import EventBus from "@/utils/EventBus";

import { useCommon } from "./Common";
const CommonStore = useCommon()

export const useVersion = defineStore('Version', {
    state: (): VersionState => {
        return {
            loading: false,
            searchForm: {
                deviceType: '',
                versionId: ''
            },
            addForm: {
                versionId: '',
                deviceType: '',
                updateInfo: '',
                file: [],
            },
            tableData: [],
            progressLong: 0,
            showProgress: false,
        }
    },
    actions: {
        async getVersion() {
            this.loading = true
            try {
                const data = await getVersionApi
                    (this.searchForm) as any

                this.tableData = data
                this.tableData.forEach((item: any, index: number) => {
                    item.index = index + 1
                })
                CommonStore.getVersion()
            } finally {
                this.loading = false
            }
        },
        async addVersion() {
            const formData = new FormData()
            for (const key in this.addForm) {
                if (key == 'file') {
                    formData.append(key, this.addForm[key][0])
                } else {
                    formData.append(key, this.addForm[key])
                }
            }
            try {
                this.showProgress = true
                const data = await addVersionApi(formData, {
                    timeout: 60000,
                    onUploadProgress: (progressEvent: any) => {
                        this.progressLong = Math.floor(progressEvent.progress * 100)
                    }
                }) as any
                if (!data) {
                    this.showProgress = false
                    EventBus.emit('UploadSuccess')
                    this.getVersion()
                    CommonStore.getVersion()
                }
            } finally { }
        },
        async delVersion(id: number) {
            try {
                const data = await delVersionApi({ id }) as any
                if (!data) {
                    EventBus.emit('DeleteSuccess')
                    this.getVersion()
                    CommonStore.getVersion()
                }
            } finally { }
        }
    }
})